package tt.dz.appaction;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import tt.dz.appaction.base.BaseController;
import tt.dz.common.Constants;
import tt.dz.common.PublicFunc;
import tt.dz.entity.UserMember;
import tt.dz.entity.UserPayCard;
import tt.dz.service.UserMemberService;
import tt.dz.service.UserPayCardService;
import tt.dz.service.UserWalletService;

/**
 * 用户信息操作控制器
 * @author xielf
 * http://download.eclipse.org/egit/updates/
 */
@Controller
@RequestMapping("/user")
public class UserInfoController extends BaseController {

	/**用户业务接口注入*/
	@Resource
	UserMemberService userMemberService;
	
	/**用户支付卡接口注入*/
	@Resource
	UserPayCardService payCardService;
	
	/**用户钱包接口注入*/
	UserWalletService userWalletService;
	
	/**
	 * 查询用户列表
	 * @param pageNo	页码
	 * @param pageSize	每页显示个数
	 */
	@RequestMapping("/getUserInfo.do")
	public void getUserInfo(Integer pageNo,Integer pageSize,HttpServletResponse response){
		
		List<UserMember> userMembers = null;
		//返回JSON
		String resultStr = "";
		try {
			userMembers = userMemberService.getUserInfoList(pageNo, pageSize);
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.SUCCESS, "ok", userMembers);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, e.getMessage(), null);
		}
		this.outJson(resultStr, response);
	}
	

	/**
	 * 根据单个用户卡号获取单个用户信息
	 * @param userid	会员ID
	 * @param request
	 * @param response
	 */
	@RequestMapping("/getUserInfoByCardNum.do")
	public void getUserInfoByCardNum(String cardNum, HttpServletRequest request,HttpServletResponse response){
	
		String resultStr = "";
		try {
			//得到用户信息
			UserMember userMember = userMemberService.getUserInfoByPayCard(cardNum);
			//JSON MAP映射表
			Map<String,Object> userCardMap = new HashMap<String,Object>();
			
			//用户信息加入MAP
			userCardMap.put("userMember", userMember);
			
			//如果用户不为空
			if(userMember!=null){
				//查询支付卡信息
				UserPayCard userPayCard = payCardService.getUserPayCardByUserId(userMember.getUserid());
				//如果卡信息不为空
				if(userPayCard!=null){
					//存入JSON
					userCardMap.put("userPayCard", userPayCard.getUser_card());
				}
				else{
					//支付卡信息为空节点存入“”
					userCardMap.put("userPayCard", "");
				}
			}
			else{
				//用户信息为空，支付卡信息节点存入“”
				userCardMap.put("userPayCard", "");
			}
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.SUCCESS, "ok", userCardMap);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, e.getMessage(), null);
		}
		this.outText(resultStr, response);
	}
	
	/**
	 * 根据多个userid获取用户集合信息
	 * @param userid	会员ID
	 * @param request
	 * @param response
	 */
	@RequestMapping("/userInfo.do")
	public void userInfo(String userid, HttpServletRequest request,HttpServletResponse response){
		
		List<UserMember> userMembers = null;
		//json返回字符串
		String resultStr = "";
		try {
			userMembers = this.userMemberService.getUserInfoByUserId(userid);
			List<Map<String,Object>> userCardMapList = new ArrayList<Map<String,Object>>();
			
			//增强循环
			for (UserMember userMember : userMembers) {
				
				//查询用户支付卡信息
				UserPayCard userPayCard = payCardService.getUserPayCardByUserId(userMember.getUserid());
				Map<String,Object> userCardMap = new HashMap<String,Object>();
				//将用户信息加入Map表中
				userCardMap.put("userMember", userMember);
				
				//支付卡信息为空
				if(userPayCard!=null){
					userCardMap.put("userPayCard", userPayCard.getUser_card());
				}
				else{
					userCardMap.put("userPayCard", "");
				}
				//加入集合
				userCardMapList.add(userCardMap);
			}
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.SUCCESS, "ok", userCardMapList);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, e.getMessage(), null);
		}
		this.outText(resultStr, response);//返回至客户端
	}
	
	/**
	 * 用户注册接口
	 * @param userMember 会员对象信息
	 * @param request
	 * @param response
	 */
	@RequestMapping("/register.do")
	public void registerUserInfo(UserMember userMember,String areaNum,HttpServletRequest request,HttpServletResponse response){
		
		//明文密码
		String clearPassword = userMember.getPassword();
		//用户加密随机KEY
		String encrypt = PublicFunc.getRandString();
		//设置KEY
		userMember.setEncrypt(encrypt);
		
		//密文密码(密码MD5编码)
		String cipherPassword = PublicFunc.MD5(PublicFunc.MD5(clearPassword)+encrypt);
		//设置密文密码
		userMember.setPassword(cipherPassword);
		
		/**开始注册*/
		String resultStr = "";
		UserMember member = null;
		try {
			String code = this.userMemberService.register(userMember,areaNum);

			//JSON MAP映射表
			Map<String,Object> userCardMap = new HashMap<String,Object>();
			//是否操作成功
			if(code.equals(Constants.JsonResponseCode.SUCCESS)){
				member = userMemberService.getUserInfoByUserId(userMember.getUserid());
				//用户信息加入MAP
				userCardMap.put("userMember", member);
				//如果用户不为空
				if(userMember!=null){
					//查询支付卡信息
					UserPayCard userPayCard = payCardService.getUserPayCardByUserId(member.getUserid());
					//如果卡信息不为空
					if(userPayCard!=null){
						//存入JSON
						userCardMap.put("userPayCard", userPayCard.getUser_card());
					}
					else{
						//支付卡信息为空节点存入“”
						userCardMap.put("userPayCard", "");
					}
				}
				
			}
			resultStr = PublicFunc.getOutStr(code, "ok", userCardMap);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, e.getMessage(), null);
		}
		this.outText(resultStr, response);//返回至客户端
	}
	
	/**
	 * 用户登录
	 * @param username	用户名
	 * @param password	密码
	 */
	@RequestMapping("/userLogin.do")
	public void userInfoLogin(String username,String password,Integer areaNum,HttpServletRequest request,HttpServletResponse response){
		
		UserMember userMember = null;
		String resultStr = "";
		try {
			//登录
			userMember = userMemberService.login(username, password, areaNum);
			//是否登录成功
			if(userMember!=null){

				//用户未激活
				if("0".equals(userMember.getActivated())){
					resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.ACCOUNT_NOT_ACTIVATION, "err", null);
				}
				//账号被禁用
				else if("2".equals(userMember.getActivated())){
					resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.ACCOUNT_DISABLED, "err", null);
				}
				//账户异常
				else if("3".equals(userMember.getActivated())){
					resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.ACCOUNT_ABNORMAL, "err", null);
				}
				//账户正常
				else{
					UserPayCard userPayCard = payCardService.getUserPayCardByUserId(userMember.getUserid());
					Map<String,Object> userCardMap = new HashMap<String,Object>();

					//用户信息加入MAP
					userCardMap.put("userMember", userMember);

					//支付卡信息不为空
					if(userPayCard!=null){
						userCardMap.put("userPayCard", userPayCard.getUser_card());
					}
					else{
						userCardMap.put("userPayCard", "");
					}
					//设置最后登录时间
					userMember.setLastdate(new Date());
					//设置登录次数
					userMember.setLoginnum(userMember.getLoginnum()+1);
					//设置最后登录IP
					userMember.setLastip(request.getRemoteAddr());
					//修改用户信息（登录次数和最后登录时间以及最后登录IP地址）
					userMemberService.updateUserInfo(userMember);
					resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.SUCCESS, "ok", userCardMap);
				}
			}
			else{
				resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.USERNAME_PWD_ERR, "err", userMember);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, e.getMessage(), null);
		}
		this.outText(resultStr, response);//返回至客户端
	}
	
	/**
	 * 更新用户位置
	 * @param userid 用户ID
	 * @param userMember 用户对象
	 * @param request
	 * @param response
	 */
	@RequestMapping("/updateUserLocation.do")
	public void updateUserLocation(Integer userId,Double lat,Double lng,HttpServletRequest request,HttpServletResponse response){
		
		String resultStr = "";
		/*开始修改位置*/
		try {
			userMemberService.updateUserLocation(userId, lat, lng);
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.SUCCESS, "ok", null);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, e.getMessage(), null);
		}
		this.outText(resultStr, response);//返回至客户端
	}
	
	/**
	 * 更改用户数据
	 * @param userMember	会员对象
	 * @param request
	 * @param response
	 */
	@RequestMapping("/updateUserInfo.do")
	public void updateUserInfo(UserMember userMember,HttpServletRequest request,HttpServletResponse response){
		
		String resultStr = "";
		//修改用户信息
		try {
			userMemberService.updateUserInfo(userMember);
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.SUCCESS, "ok", null);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, e.getMessage(), null);
		}
		this.outText(resultStr, response);//返回至客户端
	}
	
	/**
	 * 更改用户数据 IM数据
	 * @param userId
	 * @param chatUsername
	 * @param chatPassword
	 * @param request
	 * @param response
	 */
	@RequestMapping("/updatePassword.do")
	public void updatePassword(Integer userId,String oldPassword,String newPassword,HttpServletRequest request,HttpServletResponse response){
		
		String resultStr = "";
		
		try {
			/**开始修改密码*/
			String code = userMemberService.updatePassword(userId, oldPassword, newPassword);
			resultStr = PublicFunc.getOutStr(code, "ok", null);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, "err", null);
		}
		this.outText(resultStr, response);
	}

	/**
	 * 删除用户关联数据
	 * @param userId	用户ID
	 * @param request
	 * @param response
	 */
	@RequestMapping("/deleteUserRelation.do")
	public void deleteUserRelation(Integer userId,HttpServletRequest request,HttpServletResponse response){
		
		String resultStr = "";
		try {
			/**开始删除*/
			userMemberService.physicallyDeleteUserRelationById(userId);
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.SUCCESS, "ok", null);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, "ok", null);
		}
		this.outText(resultStr, response);
	}
	
	/**
	 * 获取附近用户
	 * @param lat 纬度
	 * @param lng	经度
	 * @param response
	 */
	@RequestMapping("getNearUserInfo.do")
	public void getNearUserInfo(Double lat,Double lng,Integer pageNo,Integer pageSize,HttpServletResponse response){
		
		String resultStr = "";
		try {
			if(pageNo==null || pageNo<=0){
				pageNo=1;
			}
			if(pageSize==null || pageSize<=0){
				pageSize=10;
			}
			//返回数据JSON集合
			List<Map<String,Object>> resultMapList = new ArrayList<Map<String,Object>>();
			//用户列表
			List<UserMember> members = userMemberService.getNearUserInfo(lat, lng, pageNo, pageSize);
			for (UserMember userMember : members) {
				Map<String,Object> map = new HashMap<String, Object>();
				//查询距离
				Double distance = userMemberService.getDistanceByUserIdAndLatLng(lat, lng, userMember.getUserid());
				//加入map用户JSON解析
				map.put("userMember", userMember);
				map.put("distance", distance);
				//加入JSON集合
				resultMapList.add(map);
			}
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.SUCCESS, "ok", resultMapList);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = PublicFunc.getOutStr(Constants.JsonResponseCode.DATABASE_OP_ERROR, "ok", null);
		}
		this.outText(resultStr, response);
	}
}
